package org.springblade.modules.notice.core.channel.impl;

import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.utils.message.domain.MessageParam;
import org.springblade.common.utils.message.domain.SendRequest;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.modules.notice.core.channel.BaseNoticeHandler;
import org.springblade.modules.notice.core.channel.NoticeHandler;
import org.springblade.modules.notice.enums.ChannelType;
import org.springblade.modules.notice.vo.NoticeTask;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @Author ysq
 * @Date 2024/11/26
 * @Description 微信公众号通知处理类
 */
@Slf4j
@Component
public class OfficialNoticeHandler extends BaseNoticeHandler implements NoticeHandler {

	public OfficialNoticeHandler() {
		channelTypeCode = ChannelType.OFFICIAL_ACCOUNT.getCode();
	}

	private static final String REPAIR_MINI_APPID = "wxb8dc0f5451620604";
	private static final String ESTATE_MINI_APPID = "wx92a599ff82b568e9";

	@Override
	public void handle(NoticeTask task) throws Exception {
		log.info("微信公众号通知处理 param: {}", JSONObject.toJSONString(task));
		// 构造消息
		Map<String, String> variablesMap = new HashMap<>(4);
		variablesMap.put("content", JSONObject.toJSONString(task.getTemplateVariables()));
		if (task.getTemplateVariables().containsKey("url")) {
			variablesMap.put("url", task.getTemplateVariables().get("url"));
		}
		// 处理小程序跳转参数
		if (task.getClientType() == 1) {
			// 维保小程序appid
			variablesMap.put("miniProgramId", REPAIR_MINI_APPID);
		}
		if (task.getClientType() == 2) {
			// 物业小程序appid
			variablesMap.put("miniProgramId", ESTATE_MINI_APPID);
		}

		Map<String, Object> callback = MapUtil.ofEntries(
			MapUtil.entry("bizId", String.valueOf(task.getBizId())),
			MapUtil.entry(BladeConstant.MDC_TENANT_ID_KEY, task.getTenantId())
		);
		Optional.ofNullable(task.getCallback()).ifPresent(callback::putAll);

		SendRequest sendRequest = SendRequest.builder()
			.messageTemplateId(String.valueOf(task.getMiddlePlatformTemplateId()))
			.messageParam(MessageParam.builder()
				.receiver(task.getReceiver())
				.variables(variablesMap)
				.callback(callback)
				.build())
			.build();
		messageCenter.sendMessage(sendRequest);
	}
}
